package com.fingard.dsp.bank.directbank.jrtt02;

import com.bytedance.ea.bankconnector.api.PaymentExecuteService;
import com.bytedance.ea.bankconnector.api.PaymentQueryService;
import com.bytedance.ea.bankconnector.api.dto.*;
import com.bytedance.ea.bankconnector.api.utils.SignatureUtil;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IForeignCurrencyCJ;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.frgcurrsingle.ReqCJFrgCurrSingleBat;
import com.fingard.dsp.bank.reqrespobj.frgcurrsingle.ReqQryCJFrgCurrSingleBat;
import com.fingard.dsp.bank.reqrespobj.frgcurrsingle.RetAtsCJFrgCurrSingleBat;
import com.fingard.dsp.bank.reqrespobj.frgcurrsingle.detail.CJFrgCurrSingleDetail;
import com.fingard.dsp.bank.reqrespobj.frgcurrsingle.detail.RetAtsCJFrgCurrSingleDetail;
import com.fingard.text.StringHelper;

import java.sql.Connection;
import java.util.*;

/**
 * 财经-海外接口
 */
public class JRTT02ForeignCurrencyCJ extends JRTT02Base implements IForeignCurrencyCJ {

    private static final String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
    private static final String SELECTSEQ = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? AND BANKCODE=?;";
    private static final String SELECTSEQ2 = "SELECT REQSEQID FROM REQSEQIDMAPPING WHERE BANKREQSEQID=? AND BANKCODE=?;";

    /**
     * 付款
     * @param reqCJFrgCurrSingleBat
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec foreignCurrPayCJ_BAT(ReqCJFrgCurrSingleBat reqCJFrgCurrSingleBat) throws Exception {
        //返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(reqCJFrgCurrSingleBat.reqHeader);
        //开启数据库，记录当是CITI-WL-RUB时，做流水号映射
        Connection conn= FGBiz.getLocalDbConn();
        try{
            //获取请求字段信息集合 list<PaymentInfo>
            List<PaymentInfoDto> paymentInfoList=new ArrayList<PaymentInfoDto>();
            //list<PaymentInfo>
            int count=0;//统计数量
            while (reqCJFrgCurrSingleBat.readRecord()) {
                PaymentInfoDto paymentInfo=new PaymentInfoDto();
                CJFrgCurrSingleDetail tmpDetail = reqCJFrgCurrSingleBat.readedDetail;
                if(StringHelper.hasAnyChar(tmpDetail.name) && StringHelper.hasAnyChar(tmpDetail.value)){
                    //================付款流水号处理start================
                    String askNumber="";//唯一请求流水号
                    Map<String, Object> selMap=JDBCHelper.execQuerySingle(conn,SELECTSEQ,new Object[]{tmpDetail.askNumber,reqCJFrgCurrSingleBat.reqHeader.bankCode});
                    if(selMap.size()>0){//存在，说明是重发，取原映射请求流水
                        askNumber=selMap.get("BANKREQSEQID").toString();
                    }else {//不存在，生成符合请求要求的唯一流水号
                        askNumber=getReqId(tmpDetail.askNumber,tmpDetail.name,tmpDetail.value,tmpDetail.fieldNum);
                        //记录ats支付流水号对应的银行支付流水号，供查询状态接口使用
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                        JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, reqCJFrgCurrSingleBat.reqHeader.bankCode, Format.Date8Format.format(new Date()), tmpDetail.askNumber, askNumber});
                    }
                    //================付款流水号处理end================
                    //流水号
                    paymentInfo.setEndToEndId(askNumber);
                    //list<FiledValue>
                    List<FieldValue> filedValueList=xmlWriterBodyByRpc2(tmpDetail.name,tmpDetail.value,tmpDetail.fieldNum);
                    if(filedValueList!=null && filedValueList.size()>0){
                        FieldValue filedValue=new FieldValue();
                        filedValue.setFiledName("TemplateName");
                        filedValue.setValue(tmpDetail.templateName);
                        filedValueList.add(filedValue);
                    }else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "付款信息异常";
                        retAts.writeRetToATS();
                        return retAts;
                    }
                    paymentInfo.setPaymentFields(filedValueList);
                }else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "请求name或value不能为空";
                    retAts.writeRetToATS();
                    return retAts;
                }
                paymentInfoList.add(paymentInfo);
                count++;
            }
            if(count!=Integer.parseInt(reqCJFrgCurrSingleBat.totalNum)){
                WriteBankLogLn("DetailRecord总数据与RecordNum不一致");
                retAts.respCode = "-1";
                retAts.respInfo = "DetailRecord总数据与RecordNum不一致";
                retAts.writeRetToATS();
                return retAts;
            }
            //BaseReq
            JRTT02Header jrtt02Header=new JRTT02Header();
            jrtt02Header.groupId=reqCJFrgCurrSingleBat.reqBatchNO;
            jrtt02Header.appId=getBankConfig().getValueAsString("appId");//
            jrtt02Header.signature="";//签名
            BankBaseReq ruleBaseReq=writeBankBaseReq(jrtt02Header);
            PaymentExecuteReq paymentExecuteReq=new PaymentExecuteReq();
            paymentExecuteReq.setBaseReq(ruleBaseReq);
            paymentExecuteReq.setPayments(paymentInfoList);
            paymentExecuteReq.setTotalAmount(Integer.parseInt(amountChange2(reqCJFrgCurrSingleBat.totalAmt)));
            paymentExecuteReq.setTotalCount(Integer.parseInt(reqCJFrgCurrSingleBat.totalNum));
            //签名
            String signature=SignatureUtil.sign(paymentExecuteReq,getBankConfig().getValueAsString("secret"));
            paymentExecuteReq.getBaseReq().setSignature(signature);
            //调用
            DubboBeanFactory beanFactory = new DubboBeanFactory(bankFront,getBankConfig());
            PaymentExecuteService.Iface executeClient=beanFactory.getPayService();
            WriteBankLogStep2("PaymentExecuteReq："+paymentExecuteReq);
            PaymentExecuteRsp paymentExecuteRsp=executeClient.execute(paymentExecuteReq);
            WriteBankLogStep3("PaymentExecuteRsp："+paymentExecuteRsp);
            //处理响应报文
            if (paymentExecuteRsp.getBaseRsp()!=null) {
                String returnCode = paymentExecuteRsp.getBaseRsp().getResponseStatus().trim();//返回码
                String returnMsg = paymentExecuteRsp.getBaseRsp().getAddtlInf();//返回信息
                retAts.respCode = "0";
                retAts.respInfo=returnMsg;
                retAts.reqSeqID = reqCJFrgCurrSingleBat.reqBatchNO;
                retAts.transState = returnCode;
                retAts.payInfoCode = retAts.transState;
                List<PaymentExecuteResult> paymentExecuteResultList=paymentExecuteRsp.getPaymentInfos();
                if(paymentExecuteResultList!=null && paymentExecuteResultList.size()>0){
                    StringBuilder sbd=new StringBuilder(" ");
                    for (PaymentExecuteResult paymentExecuteResult:paymentExecuteResultList){
                        String transState=paymentExecuteResult.getStatus();//付款状态
                        sbd.append(paymentExecuteResult.getEndToEndId()).append(" ");
                        sbd.append(paymentExecuteResult.getMessage()).append(" ");
                        if("ERRO".equals(transState)){
                            List<FieldVerifyMessage> filedVerifyMessageList=paymentExecuteResult.getPaymentFields();
                            if(filedVerifyMessageList!=null && filedVerifyMessageList.size()>0){
                                for(FieldVerifyMessage filedVerifyMessage:filedVerifyMessageList){
                                    sbd.append(filedVerifyMessage.getMessage()).append(",");
                                }
                            }
                            if(sbd.length()>=1){
                                sbd.deleteCharAt(sbd.length()-1).toString();
                            }
                        }
                    }
                    retAts.respInfo=retAts.respInfo+sbd;
                }
            }else{
                retAts.reqSeqID = reqCJFrgCurrSingleBat.reqBatchNO;
                retAts.respCode = "0";
                retAts.respInfo = "响应BaseRsp为空";
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = retAts.transState;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn("付款异常："+ex);
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = reqCJFrgCurrSingleBat.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 付款状态查询
     * @param reqQryCJFrgCurrSingleBat
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsCJFrgCurrSingleBat qryForeignCurrPayCJ_BAT(ReqQryCJFrgCurrSingleBat reqQryCJFrgCurrSingleBat) throws Exception {
        RetAtsCJFrgCurrSingleBat retAts=new RetAtsCJFrgCurrSingleBat(reqQryCJFrgCurrSingleBat.reqHeader);
        Connection conn= FGBiz.getLocalDbConn();
        try{
            //BaseReq
            JRTT02Header jrtt02Header=new JRTT02Header();
            jrtt02Header.groupId="";
            jrtt02Header.appId=getBankConfig().getValueAsString("appId");
            jrtt02Header.signature="";
            BankBaseReq ruleBaseReq=writeBankBaseReq(jrtt02Header);
            //list<PaymentQueryDto>
            List<PaymentQueryDto> paymentQueryDtoList=new ArrayList<PaymentQueryDto>();
            //拼接请求报文体
            while (reqQryCJFrgCurrSingleBat.readRecord()) {
                PaymentQueryDto paymentQueryDto=new PaymentQueryDto();
                Map<String, Object> selMap=JDBCHelper.execQuerySingle(conn,SELECTSEQ,new Object[]{reqQryCJFrgCurrSingleBat.readedDetail.askNumber,reqQryCJFrgCurrSingleBat.reqHeader.bankCode});
                if(selMap.size()>0){
                    paymentQueryDto.setEndToEndId(selMap.get("BANKREQSEQID").toString());//批内流水
                }else {
                    paymentQueryDto.setEndToEndId(reqQryCJFrgCurrSingleBat.readedDetail.askNumber);//批内流水
                }
                paymentQueryDto.setBankType(reqQryCJFrgCurrSingleBat.readedDetail.bankType);//银行类型
                paymentQueryDto.setPayAccount(reqQryCJFrgCurrSingleBat.readedDetail.payAct);//付方账号
                paymentQueryDto.setPayBankSwiftCode(reqQryCJFrgCurrSingleBat.readedDetail.paySWIFTCODE);//付方银行swifitCode
                paymentQueryDtoList.add(paymentQueryDto);
            }
            PaymentQueryReq paymentQueryReq=new PaymentQueryReq();
            paymentQueryReq.setBaseReq(ruleBaseReq);
            paymentQueryReq.setQueryDtos(paymentQueryDtoList);
            //签名
            String signature=SignatureUtil.sign(paymentQueryReq,getBankConfig().getValueAsString("secret"));
            paymentQueryReq.getBaseReq().setSignature(signature);
            //调用
            DubboBeanFactory beanFactory = new DubboBeanFactory(bankFront,getBankConfig());
            PaymentQueryService.Iface executeClient=beanFactory.getPayQueryService();
            WriteBankLogStep2("PaymentQueryReq："+paymentQueryReq);
            PaymentQueryRsp paymentQueryRsp=executeClient.execute(paymentQueryReq);
            WriteBankLogStep3("PaymentExecuteRsp："+paymentQueryRsp);
            //处理报文
            if (paymentQueryRsp.getBaseRsp()!=null) {
                String returnCode = paymentQueryRsp.getBaseRsp().getResponseStatus().trim();//返回码
                String returnMsg = paymentQueryRsp.getBaseRsp().getAddtlInf()==null?"":paymentQueryRsp.getBaseRsp().getAddtlInf();//返回信息
                if ("ACCP".equals(returnCode)) {
                    retAts.batRespCode = "0";
                    retAts.batRespInfo = returnMsg;
                    List<PaymentQueryResultDto> paymentQueryResultDtoList=paymentQueryRsp.getQueryDtos();
                    if(paymentQueryResultDtoList!=null && paymentQueryResultDtoList.size()>0){
                        for(PaymentQueryResultDto paymentQueryResultDto:paymentQueryResultDtoList){
                            RetAtsCJFrgCurrSingleDetail retAtsCheckDetail = new RetAtsCJFrgCurrSingleDetail();
                            String msgMiddle = paymentQueryResultDto.getMsgMiddle();//中间件返回消息
                            String msgFile = paymentQueryResultDto.getMsgFile();//中间件返回消息
                            String msgInst = paymentQueryResultDto.getMsgInst();//中间件返回消息
                            if(StringHelper.hasAnyChar(paymentQueryResultDto.getEndToEndId())){
                                Map<String, Object> selMapToAts=JDBCHelper.execQuerySingle(conn,SELECTSEQ2,new Object[]{paymentQueryResultDto.getEndToEndId().trim(),reqQryCJFrgCurrSingleBat.reqHeader.bankCode});
                                if(selMapToAts.size()>0){
                                    retAtsCheckDetail.reqSeqID = selMapToAts.get("REQSEQID").toString();
                                }else {
                                    retAtsCheckDetail.reqSeqID = paymentQueryResultDto.getEndToEndId().trim();
                                }
                                retAtsCheckDetail.outTransID = paymentQueryResultDto.getEndToEndId().trim();
                                retAtsCheckDetail.respCode = "0";
                                retAtsCheckDetail.respInfo = returnMsg+" "+msgMiddle + " " + msgFile + " " + msgInst;
                                retAtsCheckDetail.transState = paymentQueryResultDto.getPaymentStatus();//付款状态
                                retAtsCheckDetail.payInfoCode = retAtsCheckDetail.transState;
                                retAtsCheckDetail.resendFlag = getBankConfig().getMapValueByKey("resendFlagMapping", retAtsCheckDetail.transState);
                                retAts.writeRetDetail(retAtsCheckDetail);
                            }
                        }
                    }
                }else {
                    retAts.batRespCode="-1";
                    retAts.batRespInfo=returnMsg;
                }
            } else {
                retAts.batRespCode = "-1";
                retAts.batRespInfo = "响应Base为空";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.batRespCode = "-1";
            retAts.batRespInfo = ex.getMessage();
            WriteBankLogLn("付款状态查询异常："+ex);
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}
